define([ 'angular','attachments'], function(angular) {
'use strict';
	angular.module('inventory.fileItemSingle', ['app.attachments'])

	.controller('fileItemSingleCtrl'
			,['$rootScope', '$scope','systemService', 'BizData', '$uibModalInstance','params'
				, 'title', '$uibModal', '$ocLazyLoad', f])//控制器结束
	function f($rootScope, $scope, systemService, BizData, $uibModalInstance, params
			, title, $uibModal, $ocLazyLoad) {


		var common = require('common');
		var Model = this;
		
		
		//定义页面级别的变量
		var systemCode = $rootScope.winid; //系统代码
		var billType = 'ITEM';
		var billTypeName = "物料档案";
		var flowType = 0;
		var autoCode; //是否自动编码
		var revOpay; //入库出库
		var direction;
		var costingCode; //影响成本码
		var origin;
		var originName = "";
		var billNo = "";
		
		//定义页面级别的变量

		var state;
		var status;
		var orderDate;
		
		var userId;
		var enterpriseNo;
		var enterpriseName;
		
		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
		}
		
		Model.dataMasterAfterRefresh = function(event) {
			//打开窗口之后，至于编辑状态
			Model.edit();
		}
		

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataMasterAfterDelete = function(event) {
//			alert('删除之后！')
		}



		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataMasterIndexChanged = function(event) {
			/*
			if(event.rowID!=null){
				Model.dataDetail2.fMasterID = event.rowID;
	       		Model.dataDetail2.refreshData();
			}else{
				Model.dataDetail2.clearData();
			}
			*/
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataMasterDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			
			// 标准单位成本数据改变，重新计算合计单位成本
			if (event.column == "materialStandardPer" || event.column == "workingStandardPer"
					|| event.column == "manufactStandardPer" || event.column == "processStandardPer"
					) {
				var dataMaster = event.source;
				var rowID = dataMaster.getID(event.rowIndex);
				
				var materialStandardPer = dataMaster.getValue("materialStandardPer", rowID);// 到货数量
				var workingStandardPer = dataMaster.getValue("workingStandardPer", rowID);// 到货数量
				var manufactStandardPer = dataMaster.getValue("manufactStandardPer", rowID);// 到货数量
				var processStandardPer = dataMaster.getValue("processStandardPer", rowID);// 到货数量
				
				if (isNaN(materialStandardPer)) 
					materialStandardPer = 0;
				if (isNaN(workingStandardPer)) 
					workingStandardPer = 0;
				if (isNaN(manufactStandardPer)) 
					manufactStandardPer = 0;
				if (isNaN(processStandardPer)) 
					processStandardPer = 0;
				
				// 当手工改变其他科目单位成本时，重新计算单位成本
				var costingStandardPer = common.accAdd(common.accAdd(common.accAdd(materialStandardPer, workingStandardPer),manufactStandardPer),processStandardPer);
				dataMaster.setValue("costingStandardPer", costingStandardPer, rowID);
			}
			
			// 本阶成本成本数据改变，重新计算合计单位成本
			if (event.column == "workingStandardPerThis" || event.column == "manufactStandardPerThis" || event.column == "processStandardPerThis"
					) {
				var dataMaster = event.source;
				var rowID = dataMaster.getID(event.rowIndex);
				
				var workingStandardPerThis = dataMaster.getValue("workingStandardPerThis", rowID);// 到货数量
				var manufactStandardPerThis = dataMaster.getValue("manufactStandardPerThis", rowID);// 到货数量
				var processStandardPerThis = dataMaster.getValue("processStandardPerThis", rowID);// 到货数量
				
				if (isNaN(workingStandardPerThis)) 
					workingStandardPerThis = 0;
				if (isNaN(manufactStandardPerThis)) 
					manufactStandardPerThis = 0;
				if (isNaN(processStandardPerThis)) 
					processStandardPerThis = 0;
				
				// 当手工改变其他科目单位成本时，重新计算单位成本
				var costingStandardPerThis = common.accAdd(common.accAdd(workingStandardPerThis,manufactStandardPerThis),processStandardPerThis);
				dataMaster.setValue("costingStandardPerThis", costingStandardPerThis, rowID);
			}
		
			if (event.column == "qualityType"){
				var detailData = event.source;
				var rowID = detailData.getID(event.rowIndex);
				if(event.value==0){
					detailData.setValue('qualityStatus',0,rowID);
					detailData.setValue('qualityStatusLabel','0:免检',rowID);
				}
				if(event.value>0){
					detailData.setValue('qualityStatus',1,rowID);
					detailData.setValue('qualityStatusLabel','1:待验',rowID);
				}
			}

		}
		


		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataMasterBeforeNew = function(event) {

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataMasterAfterNew = function(event){

			//创建行后赋值
			event.source.setValue('systemCode',systemCode,event.id);
			event.source.setValue('billType',billType,event.id);
			event.source.setValue('billTypeName',billTypeName,event.id);
		}

		Model.dataMasterBeforeSave = function(event) {
//			console.log('dataMasterBeforeSave-->',event);
		};

		Model.dataMasterAfterSave = function(event) {
			//保存成功
			$uibModalInstance.close(0);
		};

		
		
		

		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataDetail2BeforeNew = function(event) {
			// 明细数据新增之前
			// 检查主表中的数据是否完整
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
			userId = dataMaster.getValue('userId', rowID);
			enterpriseNo = dataMaster.getValue('enterpriseNo', rowID);
			enterpriseName = dataMaster.getValue('enterpriseName', rowID);

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataDetail2AfterNew = function(event){
			var dataDetail = event.source;
			var rowID = event.id;

			dataDetail.setValue('userId', userId, rowID);
			dataDetail.setValue('enterpriseNo', enterpriseNo, rowID);
			dataDetail.setValue('enterpriseName', enterpriseName, rowID);

		}


		Model.gridRowClick = function(event){
			
			
		}

		Model.gridRowDblClick = function(event){
			Model.edit();
		}
		
		
		//打开对话框（选择仓库分类）
		Model.triggerGroupCKFLClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var groupCK = dataMaster.getValue('groupCK', rowID);
     		if(groupCK!=null && groupCK!=''){
         		dataMaster.setValue('groupCK', null, rowID);
         		dataMaster.setValue('groupCKLabel', null, rowID);
         		dataMaster.setValue('groupCKFullLabel', null, rowID);
     			return;
     		}

     		var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/inventory/groupCKFL/selectSingle',  
	            controller: 'groupCKFLSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/groupCKFL/selectSingle')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);
	             		var dataMaster = Model.dataMaster;
	             		var rowID = dataMaster.getCurrentID();

	             		//截取仓库信息
	         			dataMaster.setValue('groupCK', returnData[i].fID, rowID);
	         			dataMaster.setValue('groupCKLabel', returnData[i].groupLabel, rowID);
	         			dataMaster.setValue('groupCKFullLabel', returnData[i].groupFullLabel, rowID);

	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择商品分类）
		Model.triggerGroupSPFLClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var groupSP = dataMaster.getValue('groupSP', rowID);
     		if(groupSP!=null && groupSP!=''){
         		dataMaster.setValue('groupSP', null, rowID);
         		dataMaster.setValue('groupSPLabel', null, rowID);
         		dataMaster.setValue('groupSPFullLabel', null, rowID);
     			return;
     		}

     		var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/inventory/groupSPFL/selectSingle',  
	            controller: 'groupSPFLSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/groupSPFL/selectSingle')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);
	             		var dataMaster = Model.dataMaster;
	             		var rowID = dataMaster.getCurrentID();

	             		//截取仓库信息
	         			dataMaster.setValue('groupSP', returnData[i].fID, rowID);
	         			dataMaster.setValue('groupSPLabel', returnData[i].groupLabel, rowID);
	         			dataMaster.setValue('groupSPFullLabel', returnData[i].groupFullLabel, rowID);

	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};

		
		//打开对话框（选择会计分类）
		Model.triggerGroupKJFLClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var groupKJ = dataMaster.getValue('groupKJ', rowID);
     		if(groupKJ!=null && groupKJ!=''){
         		dataMaster.setValue('groupKJ', null, rowID);
         		dataMaster.setValue('groupKJLabel', null, rowID);
         		dataMaster.setValue('groupKJFullLabel', null, rowID);
     			return;
     		}

     		var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/inventory/groupKJFL/selectSingle',  
	            controller: 'groupKJFLSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/groupKJFL/selectSingle')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);
	             		var dataMaster = Model.dataMaster;
	             		var rowID = dataMaster.getCurrentID();

	             		//截取仓库信息
	         			dataMaster.setValue('groupKJ', returnData[i].fID, rowID);
	         			dataMaster.setValue('groupKJLabel', returnData[i].groupLabel, rowID);
	         			dataMaster.setValue('groupKJFullLabel', returnData[i].groupFullLabel, rowID);

	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择仓库）
		Model.triggerStorageNoClick = function(){
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			options.filterby = 'enterpriseNo';

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/inventory/fileStorage/selectSingle',  
	            controller: 'fileStorageSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileStorage/selectSingle')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);
	             		var dataMaster = Model.dataMaster;
	             		var rowID = dataMaster.getCurrentID();

	             		//截取仓库信息
	         			dataMaster.setValue('storageID', returnData[i].fID, rowID);
	         			dataMaster.setValue('storageNo', returnData[i].storageNo, rowID);
	         			dataMaster.setValue('storageName', returnData[i].storageName, rowID);
	         			dataMaster.setValue('storageType', returnData[i].storageType, rowID);
	         			dataMaster.setValue('storageTypeLabel', returnData[i].storageTypeLabel, rowID);
	         			dataMaster.setValue('floorNo', returnData[i].storageFullName, rowID);
	         			dataMaster.setValue('allowed', returnData[i].allowed, rowID);

	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择交易对象）
		Model.triggerProviderNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var providerNo = dataMaster.getValue('providerNo', rowID);
     		if(providerNo!=null && providerNo!=''){
         		dataMaster.setValue('storageTypeD', null, rowID);
         		dataMaster.setValue('storageTypeDLabel', null, rowID);
         		dataMaster.setValue('providerID', null, rowID);
         		dataMaster.setValue('providerNo', null, rowID);
         		dataMaster.setValue('providerShortName', null, rowID);
         		dataMaster.setValue('providerName', null, rowID);
     			
         		dataMaster.setValue('taxType', 0, rowID);
         		dataMaster.setValue('taxTypeLabel', '0.应税外加', rowID);
         		dataMaster.setValue('taxRate', 0, rowID);
     			return;
     		}

     		var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openProviderNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
	             		dataMaster.setValue('storageTypeD', returnData[i].storageTypeD, rowID);
	             		dataMaster.setValue('storageTypeDLabel', returnData[i].storageTypeDLabel, rowID);
	             		dataMaster.setValue('providerID', returnData[i].fID, rowID);
	             		dataMaster.setValue('providerNo', returnData[i].providerNo, rowID);
	             		dataMaster.setValue('providerShortName', returnData[i].shortName, rowID);
	             		dataMaster.setValue('providerName', returnData[i].providerName, rowID);
	         			
	             		dataMaster.setValue('taxType', returnData[i].taxType, rowID);
	             		dataMaster.setValue('taxTypeLabel', returnData[i].taxTypeLabel, rowID);
	             		dataMaster.setValue('taxRate', returnData[i].taxRate, rowID);
	         			
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择工作中心）
		Model.triggerWorkcenterNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var workcenterNo = dataMaster.getValue('workcenterNo', rowID);
     		if(workcenterNo!=null && workcenterNo!=''){
//         		dataMaster.setValue('procedureType', null, rowID);
//         		dataMaster.setValue('procedureTypeLabel', null, rowID);
         		dataMaster.setValue('workcenterID', null, rowID);
         		dataMaster.setValue('workcenterNo', null, rowID);
         		dataMaster.setValue('workcenterName', null, rowID);
         		dataMaster.setValue('workcenterLName', null, rowID);
     			return;
     		}

     		//如果是厂内工单CNGD
			var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openWorkcenterNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		dataMaster.setValue('workcenterID', returnData[i].fID, rowID);
	             		dataMaster.setValue('workcenterNo', returnData[i].workcenterNo, rowID);
	             		dataMaster.setValue('workcenterName', returnData[i].workcenterName, rowID);
	             		dataMaster.setValue('workcenterLName', returnData[i].workcenterLName, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		//打开对话框（选择物料）选择配置物料
		Model.triggerItemNoClick = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
			var fParent = dataMaster.getValue('fParent',rowID);
			if(fParent){
     			dataMaster.setValue('fParent', null, rowID);
				dataMaster.setValue('fParentNo', null, rowID);
				return;
			}

			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			options.configType = 1;//可配置物料
			
			var modalInstance = systemService.openItemNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var simpleRow = event.data[0];
     			dataMaster.setValue('fParent', simpleRow.fID, rowID);
				dataMaster.setValue('fParentNo', simpleRow.itemNo, rowID);
	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//获取最大排序号
		Model.triggerGetSortNoClick = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var enterpriseNo = dataMaster.getValue('enterpriseNo',rowID);
			var options = {};
			options.enterpriseNo = enterpriseNo;
			
			$.ajax({
                type: "GET",
                async : true,
                url: $rootScope.getProjectName() + "/inventory/fileItem/list/getMaxSortNoPlus",
                data: options,//rowID,// "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
//                processData: false,
                success: function (data) {
                    // Play with returned data in JSON format
                    console.log('success',data);
                    dataMaster.setValue('sortNo',data.sortNo,rowID);
                    $scope.$apply();
                },
                error: function (msg) {
                    console.log('error',msg);
                    alert('操作失败，请检查网络是否正常！');
                }
            });			
		};
		
		
		var options = {};
		options.container = Model;
		options.concept = 'FileItem';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
 		options.creater = '/inventory/fileItem/list/create';
 		options.reader = '/inventory/fileItem/list/query';
		options.writer = '/inventory/fileItem/list/save';
		options.deleter = '/inventory/fileItem/list/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.directDeleteMode = true;
		options.limit = 15;
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataMasterIndexChanged;
		options.onBeforeNew = Model.dataMasterBeforeNew;
		options.onAfterNew = Model.dataMasterAfterNew;
		options.onBeforeDelete = Model.dataMasterBeforeDelete;
		options.onAfterDelete = Model.dataMasterAfterDelete;
		options.onValueChanged = Model.dataMasterValueChanged;
		options.onDataChanged = Model.dataMasterDataChanged;
		options.onAfterRefresh = Model.dataMasterAfterRefresh;
		options.onBeforeSave = Model.dataMasterBeforeSave;
		options.onAfterSave = Model.dataMasterAfterSave;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
		
		Model.dataMaster = new BizData(options);

		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		
		var options = {};
		options.container = Model;
		options.concept = 'StorageItem';
		options.name = 'dataDetail2';
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/inventory/fileItem/list/createDetail';
		options.reader = '/inventory/fileItem/list/queryDetail';
		options.reader = '';
		options.writer = '';
		options.deleter = '';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.master = {"data":"dataMaster","relation":"itemID"};
		options.directDeleteMode = false;
		options.limit = 15;
		options.orderBy = "";
		
		options.onBeforeNew = Model.dataDetail2BeforeNew;
		options.onAfterNew = Model.dataDetail2AfterNew;

		
//		Model.dataDetail2 = new BizData(options);
		//监视对象中的所有变动
//		Model.dataDetail2.deregRows = $scope.$watch('Model.dataDetail2.rows',Model.dataDetail2.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		
		
		////////////////////启动执行开始///////////////////////////////////////////////////
		//接收调用的参数
//		Model.params = $rootScope.$stateParams;  
		
		//刷新数据
//	    Model.dataMaster.refreshData();
		
		//新建
		Model.add = function(){
		    var options = {
		    		index : 0,
		    		defaultValues : [
		    			{
			            	 state:'active'
			            	 ,status:'open'
			            	 ,audit:'active'
		            		 
			            	 ,taxRate:0
			            	 ,purchaseTaxType:1
			            	 ,purchasePrice:0.00
			            	 ,saleTaxType:1
			            	 ,salePrice:0
			            	 ,processTaxType:1
			            	 ,processPrice:0
			     			
			     			,costingType:2
			     			,qualityType:0
			     			,qualityTypeLabel:'0.免检'
			     			,qualityPeriod:0
			     			,validDays:0
			     			,checkoutAgainDays:0
			     			,checkoutDays:0
			     			
			     			,qualityStatus:0
			     			,qualityStatusLabel:'0.免检'

			     			,levelCode:'99'
			     				
			     			,configType:0
			     			
//					   		,itemProperty:'*****'
			     			,batchNo:'********************'
			     			,storeNo:'********************'
			     			,stockFlag:1
			     			,forSale:'Y'
			     			,forUsed:'Y'
			     			,process:'P'
			     			,processLabel:'P.采购件'
			     			,mpsFlag:0
			     				
				            ,checkin:1

			            	,workingHourBase:0
			            	,workingHourPlan:0
			            	,machineHourPlan:0
			            	
			            	,itemQuantityL:0
			            	,itemQuantityFrozen:0
			            	,pieceQuantityL:0
			            	,pieceQuantityFrozen:0
			            	
//				            ,materialAmount:0
//				           	,workingAmount:0
//				           	,manufactAmount:0
//				           	,processAmount:0
			            	,costingAmount:0
			            	 
//			            	,materialAmountPer:0
//			            	,workingAmountPer:0
//			            	,manufactAmountPer:0
//			            	,processAmountPer:0
			            	,costingAmountPer:0
			            	 
			            	,materialStandardPer:0
			            	,workingStandardPer:0
			            	,manufactStandardPer:0
			            	,processStandardPer:0
			            	,costingStandardPer:0
			            	 
			            	,materialStandardPerThis:0
			            	,workingStandardPerThis:0
			            	,manufactStandardPerThis:0
			            	,processStandardPerThis:0
			            	,costingStandardPerThis:0
			            	 
			            	,workingHour:0
			            	,machineHourPlan:0
			            	 
			            	,itemWeight:0
			            	,orderWeight:0
			            	 
			            	,leadTime:9999
			            	 
			            	,upperShelf:0
			            	 
			            	,billType: billType
			            	,orderDate: ':getCurrentDate()'
				            ,employeeNo: ':getCurrentPsmFID()'
					        ,employeeName: ':getCurrentPsmFName()'
				            ,cUsercode: ':getCurrentPersonCode()'
					        ,cUsername: ':getCurrentPersonName()'
						    ,cDatetime: ':getCurrentDateTime()'
							,userId: ':getCurrentPersonID()'
							,enterpriseNo: ':getCurrentOgnFID()'
							,enterpriseName: ':getCurrentOgnLongName()'
							,version: 0

			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataMaster.newData(options);
		};
		
		//修改
		Model.edit = function(){
//			Model.dataMaster.userdata.recordState = 'edit';
			Model.dataMaster.editData();
		};
        Model.ok = function () {  
        	var rowID = Model.dataMaster.getCurrentID();
        	var floorNo = Model.dataMaster.getValue('floorNo',rowID);
//        	console.log('floorNo-->',floorNo);
        	if(floorNo==null){
        		alert('默认仓库不能为空！');
        		return ;
        	}
        	
	    	Model.dataMaster.saveData();
			
	    };  
	    
	    Model.cancel = function () {  
	        $uibModalInstance.dismiss('cancel');  
	    };    

		
		//////////////////////对话框使用开始//////////////////////////////////////
        //模态窗口打开之后执行的事件
        $uibModalInstance.opened.then(function(){
    		//接收调用对话框的参数
            Model.title = title;  
            Model.params = params;  
    		 
    		if(Model.params.recordState=='new'){
    			Model.add();
    		}
    		if(Model.params.recordState=='edit'){
    			Model.dataMaster.id = Model.params.id;
    		    Model.dataMaster.refreshData();
    		}
        });  
		 
		//////////////////////对话框使用结束//////////////////////////////////////


		
		///////////////////子表2按钮组开始///////////////////////////////////////////////////
		//增加
		Model.addrow2 = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			options.filterby = 'enterpriseNo';
			
			$uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/inventory/fileStorage/selectSingle',  
	            controller: 'fileStorageSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileStorage/selectSingle')
		        }
	        }).result.then(function (event) {  
	             //确定关闭窗口
	         	var returnData = event.data;

     			var storageID = returnData[0].fID
     			var storageNo = returnData[0].storageNo;
     			var storageName = returnData[0].storageName;
     			var storageType = returnData[0].storageType;
     			var storageTypeLabel = returnData[0].storageTypeLabel;
     			var floorNo = returnData[0].storageFullName;
     			
    		    var options = {
    			        index : Model.dataDetail2.getCount(),
    			        defaultValues : [
    			        	{
    			           	 	itemID:rowID
    			           	 	,status:'open'
    			           	 		
    			        		,storageID:storageID
    			           	 	,storageNo:storageNo
    			           	 	,storageName:storageName
    			           	 	,storageType:storageType
    			           	 	,storageTypeLabel:storageTypeLabel
    			           	 	,floorNo:floorNo
			            	 
    			           	 	,quantityL:0
    			           	 	,minQuantity:0
    			           	 	,maxQuantity:0
    			           	 	,pieceQuantityL:0
    			           	 	
    			        	}
    			            //,{itemNo:'a2',itemDescribe:'b2'}
    			        ]
    			    };    

    			Model.dataDetail2.newData(options);

	        }, function (reason) {
	        	//取消关闭窗口
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		};
		
		Model.delrow2 = function() {
			//判断库存量是否为0
			var dataDetail2 = Model.dataDetail2;
			var rowID = dataDetail2.getCurrentID();
			var quantityL = dataDetail2.getValue('quantityL',rowID);
			if(quantityL!=0){
				alert('库存量不等于0，不允许删除！');
				return;
			}

			if(Model.dataDetail2.directDeleteMode){
			//直接删除
				if(Model.dataDetail2.deleteData(Model.dataDetail2.getCurrentID())==0){
				}
			}else{
			//前台移除
				if(Model.dataDetail2.removeData(Model.dataDetail2.getCurrentID())==0){
				}
			}
		};
		
		
		///////////////////子表2按钮组结束///////////////////////////////////////////////////

		
		////////////////////////////////获取成本计价方式数据开始//////////////////////////////////
		/*
		$scope.dataCostingType= {};
		var response = costingTypeService.query();
		response.success(function(data, status, headers, config) {
			$scope.dataCostingType = data;
		
		});
		response.error(function(data, status, headers, config) {
			alert( "Exception details: " + JSON.stringify({data: data}));
		});
		*/
		
		
		$scope.dataCostingType = [
			{"costingType":1,"costingTypeLabel":"1:移动加权平均"}
			,{"costingType":2,"costingTypeLabel":"2:月末一次加权平均"}
			,{"costingType":3,"costingTypeLabel":"3:先进先出X"}
			,{"costingType":4,"costingTypeLabel":"4:个别计价/分批认定X"}
			];
		
		
		
		////////////////////////////////获取成本计价方式数据结束//////////////////////////////////

		
		
	    return Model;

	}	
	
});//define结束
	
